package com.css.fxfzmh.login.security.impl;

import com.css.fxfzmh.base.user.repository.entity.CertificationEntity;
import com.css.fxfzmh.config.property.FxfzConfig;
import com.css.fxfzmh.constants.FxfzConstants;
import com.css.fxfzmh.login.security.SecretKeyRuleService;
import com.css.fxfzmh.util.UUIDGenerator;
import com.lambdaworks.crypto.SCryptUtil;
import lombok.extern.slf4j.Slf4j;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 *
 * @author lixiaofeng
 * @date 2020/4/18
 */
@Service
@Slf4j
public class SecretKeyRuleServiceImpl implements SecretKeyRuleService {
    @Autowired
    private FxfzConfig fxfzConfig;


    @Override
    public CertificationEntity encryption(CertificationEntity certificationEntity, String password) {
        if(FxfzConstants.ENCRYPTION_MD5.equals(fxfzConfig.getEncryption())){
            String salt = UUIDGenerator.getUUID();
            certificationEntity.setSalt(salt);
            //密文
            String ciphertext = SCryptUtil.scrypt(salt + password + salt, 2048, 1, 1);
            certificationEntity.setPwd(ciphertext);
            return certificationEntity;
        }
        if(FxfzConstants.ENCRYPTION_BCRYPT.equals(fxfzConfig.getEncryption())){
            String salt = BCrypt.gensalt();
            String ciphertext = BCrypt.hashpw(password, salt);
            certificationEntity.setPwd(ciphertext);
            certificationEntity.setSalt(salt);
            return certificationEntity;
        }
        log.error("login.encryption配置错误");
        return null;
    }

    @Override
    public boolean check(CertificationEntity certificationEntity, String password) {
        if (FxfzConstants.ENCRYPTION_MD5.equals(fxfzConfig.getEncryption())) {
            String salt = certificationEntity.getSalt();
            return SCryptUtil.check(salt + password + salt, certificationEntity.getPwd());
        }
        if (FxfzConstants.ENCRYPTION_BCRYPT.equals(fxfzConfig.getEncryption())) {
            return BCrypt.checkpw(password, certificationEntity.getPwd());
        }
        log.error("login.encryption配置错误");
        return false;
    }

    @Override
    public boolean check(String ciphertext, String password, String salt) {
        if (FxfzConstants.ENCRYPTION_MD5.equals(fxfzConfig.getEncryption())) {
            return SCryptUtil.check(salt + password + salt, ciphertext);
        }
        if (FxfzConstants.ENCRYPTION_BCRYPT.equals(fxfzConfig.getEncryption())) {
            return BCrypt.checkpw(password, ciphertext);
        }
        log.error("login.encryption配置错误");
        return false;
    }



}
